package com.glory.dgcpcpda.activity.mfg;

import android.os.Handler;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.WaferInListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.MLotListEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class WaferRecieveActivity extends BaseActivity {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.tvErrorOut)
    TextView tvErrorOut;

    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;

    @BindView(R.id.etLotSearch)
    FreeUI_ClearEditText etLotSearch;
    @BindView(R.id.etWaferNameSearch)
    FreeUI_ClearEditText etWaferNameSearch;

    @BindView(R.id.elResult)
    TextView elResult;

    @BindView(R.id.llMain)
    LinearLayout llMain;

    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;

    @BindView(R.id.etCustName)
    FreeUI_ClearEditText etCustName;

    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;

    @BindView(R.id.checkbox)
    CheckBox checkBox;

    private WaferInListAdapter mAdapter;
    String type="";
    String issearch="0";
    @Override
    protected int getLayoutResId() {
        return R.layout.activity_wafer_in;
    }

    @Override
    protected void initView() {
       // tvBaseSubmit.setVisibility(View.GONE);
        tvErrorOut.setVisibility(View.VISIBLE);
        tvErrorOut.setText("改数");
        tvBaseSubmit.setText("查询");
        tvState.setVisibility(View.VISIBLE);
        tvState.setText("提交");
        setMainLayout(llMain);
        tvTitle.setText("氮化镓芯片入库");
        initRecyclerView(rvLotList,this);
        mAdapter = new WaferInListAdapter(null);
        mAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mAdapter.isFirstOnly(false);
        rvLotList.setAdapter(mAdapter);

        initEdit(etLot, s -> {
            etLot.setText("");
            //如果是查询的数据，扫描物料批号会清空列表
            if(issearch.equals("1")){
                mAdapter.setNewData(null);
                issearch="0";
            }
            new Handler().postDelayed(() -> etLot.requestFocus(),500);
            String StorgeId = getText(etUserName);
            String custName=getText(etCustName);
            if(checkBox.isChecked()){
                type="down";
            }else{
                type="up";
                if ("".equals(StorgeId)){
                    showToast("请先扫描货架号！",false);
                    return;
                }
            }
            Submit(s, StorgeId,custName);
        });
    }

    @Override
    protected void initData() {

    }

    private  void  Submit(String waferLot, String STORAGEID,String custName){
        String[] mlotInfo=waferLot.split(";");
        String waferName="";//标签芯片名
        String waferLotId="";//标签芯片批号
        String wafersubqty="";//标签芯片数
        String waferDate="";//标签日期
        if(mlotInfo.length==2){
            waferName=mlotInfo[0];
            waferLotId=mlotInfo[1];
        }else{
            waferName=mlotInfo[0];
            wafersubqty=mlotInfo[5];
            waferLotId=mlotInfo[4];
            if(mlotInfo[6].length()>10){
                waferDate=mlotInfo[6].substring(0,10);
            }else{
                waferDate=mlotInfo[6];
            }
        }
        MLotListEntity MLotList=new MLotListEntity();
        MLotList.setPARTNERLOTID(waferLotId);
        MLotList.setMATERIALDESC(waferName);
        MLotList.setSUBQTY(wafersubqty);
        MLotList.setTRANSSTORAGEID(STORAGEID);
        MLotList.setRESERVED1(waferDate);
        MLotList.setPOSITION(custName);
        for(int i=0;i<mAdapter.getData().size();i++){
            //判断货架号是否一致
            if(mAdapter.getData().get(i).getTRANSSTORAGEID().equals(MLotList.getTRANSSTORAGEID())){
                //判断芯片名不一致
                if(!mAdapter.getData().get(i).getMATERIALDESC().equals(MLotList.getMATERIALDESC())){
                    showConfirmDialog("当前货架号已有芯片名:"+mAdapter.getData().get(i).getMATERIALDESC());
                    return;
                }
            }
        }
        List<MLotListEntity> list=new ArrayList<>();
        list.add(MLotList);
        mAdapter.addData(list);
    }
    @OnClick({R.id.tvBaseSubmit,R.id.checkbox,R.id.tvState,R.id.tvErrorOut})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if("".equals(etWaferNameSearch.getText().toString()) && "".equals(etLotSearch.getText().toString())){
                    showToast("请填写查询批号或者芯片名！",false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<MLotListEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<MLotListEntity>>
                        (new TypeToken<BaseResponseBean<MLotListEntity>>() {
                        }.getType(), getSupportFragmentManager(), WaferRecieveActivity.this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<MLotListEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                            String result = response.body().getResponse().getHeader().getRESULTMESSAGE();
                            List<MLotListEntity> list = response.body().getResponse().getBody().getXMLOTLIST();
                            issearch="1";//是否查询数据
                            mAdapter.setNewData(null);
                            //mAdapter.addData(list);
                            mAdapter.setNewData(list);

                        } else {
                            elResult.setText(response.body().getResponse().getHeader().getRESULTMESSAGE());
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<MLotListEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(), "RECEIVEMLOT");
                    }
                };

                JsonObject map = new JsonObject();

                map.addProperty("ACTIONTYPE", "WAFER_QUERY");
                map.addProperty("WAFERNAME", etWaferNameSearch.getText().toString());
                map.addProperty("MLOTID", etLotSearch.getText().toString());
                NetUtils.requestPostNet("CPC.RECEIVEMLOT", "TRANSFERMES",WaferRecieveActivity.this, map, callBack);
                break;
            case R.id.checkbox:
                if(checkBox.isChecked()){
                    etLot.setHint("请扫描物料批号下架");
                    mAdapter.setNewData(null);
                    etUserName.setText("");
                    etLotSearch.setText("");
                    etWaferNameSearch.setText("");
                    etLot.setFocusable(true);
                    etLot.requestFocus();
                    etLot.setFocusableInTouchMode(true);
                    etLot.requestFocusFromTouch();
                }else{
                    etLot.setHint("请扫描物料批号上架");
                    mAdapter.setNewData(null);
                }

                break;
            case R.id.tvState:
                //如果是查询的数据，提交则会卡控
                if(issearch.equals("1")){
                    if ("up".equals(type)) {
                        showToast("请扫描货架号和物料批号！",false);
                        return;
                    }else{
                        showToast("请扫描物料批号！",false);
                        return;
                    }
                }
                if(mAdapter.getData().size()==0){
                    if ("up".equals(type)) {
                        showToast("请扫描货架号和物料批号！",false);
                        return;
                    }else{
                        showToast("请扫描物料批号！",false);
                        return;
                    }
                }
                FreeUI_EntityCallBack<BaseResponseBean<MLotListEntity>> callBack1 = new CustomDialogEntityCallBack<BaseResponseBean<MLotListEntity>>
                        (new TypeToken<BaseResponseBean<MLotListEntity>>() {
                        }.getType(), getSupportFragmentManager(), WaferRecieveActivity.this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<MLotListEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                            String result = response.body().getResponse().getHeader().getRESULTMESSAGE();
                            List<MLotListEntity> list = response.body().getResponse().getBody().getXMLOTLIST();
                            if ("up".equals(type)) {
                                if ("".equals(result)) {
                                    result = "上架成功！！！";
                                }
                            }else{
                                result = "下架成功！！！";
                            }
                            showToast(result, true);
                            etLot.setText("");
                            etLot.setFocusable(true);
                            elResult.setText(result);
                            mAdapter.setNewData(null);

                        }else {
                            elResult.setText(response.body().getResponse().getHeader().getRESULTMESSAGE());
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<MLotListEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"RECEIVEMLOT");
                    }
                };
                JsonObject map1 = new JsonObject();
                if("up".equals(type)){
                    map1.addProperty("ACTIONTYPE", "WAFER_RECIEVE");
                }else{
                    map1.addProperty("ACTIONTYPE", "WAFER_DOWN");
                }
                map1.addProperty("WAREHOUSEID","705_WAFER_DQG");
                List<MLotListEntity> waferList = new ArrayList<>();
                for(MLotListEntity entity : mAdapter.getData()){
                    waferList.add(entity);
                }
                map1.add("WAFERLIST", new JsonParser().parse(new Gson().toJson(waferList)).getAsJsonArray());
                NetUtils.requestPostNet("CPC.RECEIVEMLOT", "TRANSFERMES",WaferRecieveActivity.this,map1,callBack1);
                break;
            case R.id.tvErrorOut:
                //改数
                if(mAdapter.getData().size()==0){
                    showToast("请先查询数据！",false);
                    return;
                }
                FreeUI_EntityCallBack<BaseResponseBean<MLotListEntity>> callBack2 = new CustomDialogEntityCallBack<BaseResponseBean<MLotListEntity>>
                        (new TypeToken<BaseResponseBean<MLotListEntity>>() {
                        }.getType(), getSupportFragmentManager(), WaferRecieveActivity.this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<MLotListEntity>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())) {
                            String result = response.body().getResponse().getHeader().getRESULTMESSAGE();
                            List<MLotListEntity> list = response.body().getResponse().getBody().getXMLOTLIST();
                            result = "改数成功！！！";
                            showToast(result, true);
                            etLot.setText("");
                            etLot.setFocusable(true);
                            elResult.setText(result);
                            mAdapter.setNewData(null);

                        }else {
                            elResult.setText(response.body().getResponse().getHeader().getRESULTMESSAGE());
                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<MLotListEntity>> response) {
                        super.onError(response);
                        loadError(response.getException(),"RECEIVEMLOT");
                    }
                };
                JsonObject map2 = new JsonObject();
                map2.addProperty("ACTIONTYPE", "WAFER_UPDATEQTY");
                map2.addProperty("WAREHOUSEID","705_WAFER_DQG");
                List<MLotListEntity> waferList1 = new ArrayList<>();
                for(MLotListEntity entity : mAdapter.getData()){
                    waferList1.add(entity);
                }
                map2.add("WAFERLIST", new JsonParser().parse(new Gson().toJson(waferList1)).getAsJsonArray());
                NetUtils.requestPostNet("CPC.RECEIVEMLOT", "TRANSFERMES",WaferRecieveActivity.this,map2,callBack2);
                break;
        }
    }
}